<template>
  <section class="component relation-checkbox">
    <el-form label-width="100px">
      <el-form-item label="请选择发送对象:">
        <el-checkbox :indeterminate="indeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>

        <el-checkbox-group v-model="checkedModel" @change="handleCheckedRealtionChange">
          <el-checkbox v-for="{index,name,code} in relations" :label="code" :key="index" :value="code">{{name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
  </section>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component';
import { Dependencies } from '~/core/decorator';
import { Emit, Prop, Model} from 'vue-property-decorator';

@Component({})
export default class RelationCheckbox extends Vue {

  private indeterminate: boolean = false
  private checkAll: boolean = false
  @Model('on-change')
  private checkedRelation: any[]
  @Emit('on-change')
  private onChange(val) {}

  private set checkedModel(val) {
    this.onChange(val)
  }

  private get checkedModel() {
    if (this.checkedRelation.length === 0) {
      this.indeterminate = false
      this.checkAll = false
    }
    return this.checkedRelation
  }

  private get relations() {
    return this.$dict.getDictData('Relationship')
  }

  private handleCheckAllChange(val) {
    const arr: any[] = !val ? [] : this.relations.map(e => e.code)
    this.onChange(arr)
    this.indeterminate = false
  }

  private handleCheckedRealtionChange(val) {
    this.onChange(val)
    const count: number = val.length
    this.checkAll = count === this.relations.length
    this.indeterminate = count > 0 && count < this.relations.length
  }

}
</script>

